package top.wardyan.base.service.impl;

import java.util.LinkedList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import top.wardyan.base.service.IProceduceService;
import top.wardyan.base.sqlserver.proc.Parameter;
import top.wardyan.base.sqlserver.proc.ParameterType;
import top.wardyan.base.sqlserver.proc.Proceduce;

/**
 * 查询存储过程 接口的实现类
 * @author ward
 *
 * 2019年2月2日
 */
public class ProceduceServiceImpl implements IProceduceService{
	
	protected static final String sql = "SELECT m.name AS xProcName, d.name AS xParaName, t.name AS xType, d.max_length as xLength, d.is_output AS xIsOutput FROM sys.procedures AS m "
											+ "LEFT JOIN sys.parameters AS d ON m.object_id = d.object_id " 
											+ "INNER JOIN sys.types AS t ON d.system_type_id = t.system_type_id " 
											+ "WHERE m.type = 'P' AND m.name = ? AND t.name <> 'sysname' " 
											+ "ORDER BY d.parameter_id" ;

	protected String arpName;
	
	public ProceduceServiceImpl(String arpName) {
		this.arpName = arpName;
	}
	@Override
	public Proceduce find(String name) {
		List<Record> rs = Db.use(arpName).find(sql, name);
		if(rs != null && rs.size() > 0) {
			Proceduce po = 	new Proceduce()
							.setName(name);
			List<Parameter> paras = new LinkedList<Parameter>();
			for(Record r : rs) {
				paras.add(	new Parameter()
							.setName(removeAtSymbol(r.getStr("xParaName")))
							//.setIndex(r.getInt("x"));
							.setIsOutput(r.getBoolean("xIsOutput") != null && r.getBoolean("xIsOutput") ? 2 : 1)
							.setLength(r.getInt("xLength"))
							.setType(ParameterType.types.get(r.getStr("xType").toUpperCase()))
							.setTypeStr(r.getStr("xType").toUpperCase())
						);
			}
			po.setParas(paras);
			return po;
		}
		return null;
	}

	//protected abstract String getArpName();
	
	protected String removeAtSymbol(String name) {
		if(name.startsWith("@")) {
			return name.substring(1, name.length());
		}else
			return name;
	}
	
}











